<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900" :close-on-press-escape="false" :close-on-click-modal="false" center>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="merchant-form">
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商家名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入商家名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商家编码" prop="code">
            <el-input v-model="formData.code" placeholder="请输入商家编码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="isEnabled">
            <el-switch v-model="formData.isEnabled" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商家分类" prop="category">
            <el-select v-model="formData.category" placeholder="请选择商家分类" style="width: 100%">
              <el-option label="餐饮" value="餐饮" />
              <el-option label="购物" value="购物" />
              <el-option label="娱乐" value="娱乐" />
              <el-option label="服务" value="服务" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 地址信息 -->
      <el-divider content-position="left">地址信息</el-divider>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入详细地址">
          <template #append>
            <el-button :icon="Location" @click="handleShowPosition" />
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="地理位置" prop="position">
        <el-input v-model="formData.position" placeholder="经度,纬度 (如: 102.397481,25.906712)" />
      </el-form-item>

      <!-- 营业信息 -->
      <el-divider content-position="left">营业信息</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="营业时间" prop="businessHours">
            <el-input v-model="formData.businessHours" placeholder="如: 10:00 - 22:00" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="人均消费" prop="averageCost">
            <el-input-number v-model="formData.averageCost" :min="0" :max="9999" controls-position="right" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商家评分" prop="rating">
            <el-rate v-model="formData.rating" :max="5" :precision="0.1" show-score text-color="#ff9900" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业执照号" prop="businessLicenseNo">
            <el-input v-model="formData.businessLicenseNo" placeholder="请输入营业执照号" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 图片信息 -->
      <el-divider content-position="left">图片信息</el-divider>

      <el-form-item label="商家Logo">
        <div class="upload-section">
          <el-upload class="logo-uploader" :action="formAction" :show-file-list="false" :headers="fileHeader" :before-upload="beforeLogoUpload" :on-success="handleLogoSuccess">
            <img v-if="formData.logo" :src="formData.logo" class="logo-preview" />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸: 300x200px</div>
        </div>
      </el-form-item>

      <el-form-item label="商家门面图片">
        <div class="image-upload-section">
          <el-upload v-model:file-list="imageFileList" :headers="fileHeader" :action="formAction" list-type="picture-card" :before-upload="beforeImageUpload" :on-success="handleImageUpload" :on-remove="handleImageRemove">
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传5张图片</div>
        </div>
      </el-form-item>

      <!-- 标签和描述 -->
      <el-divider content-position="left">其他信息</el-divider>

      <el-form-item label="商家标签">
        <div class="tags-section">
          <el-tag v-for="tag in tags" :key="tag" closable @close="removeTag(tag)" class="tag-item">
            {{ tag }}
          </el-tag>
          <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" class="tag-input" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
          <el-button v-else class="new-tag-btn" size="small" @click="showInput"> + 添加标签 </el-button>
        </div>
      </el-form-item>

      <el-form-item label="商家描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入商家描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> {{ editMode ? '保存' : '发布商家' }} </el-button>
        <el-button size="large" @click="() => (dialogVisible = false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <LocationView ref="refLocationView" @change="handlePositionChange" />
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Location } from '@element-plus/icons-vue'
import http from '@/apis/shop'
import type { FormInstance, UploadFile, FormRules, UploadProps } from 'element-plus'
import LocationView from '@/components/location.vue'

import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const refLocationView = ref<typeof LocationView>()

const handleShowPosition = () => {
  // console.log(formData.value.position)
  refLocationView.value?.handleShow(formData.value.position)
}

interface positionType {
  location: string
  lat: number
  lng: number
}

const handlePositionChange = (obj: positionType) => {
  // console.log(obj)
  formData.value.position = obj.location
}

const submitting = ref(false)
const host = import.meta.env.VITE_BASE_URL
const dialogTitle = ref('新增数据')
const user = computed(() => userStore.userInfo)
// 表单引用
const formRef = ref<FormInstance>()
const inputRef = ref()
const formAction = ref(host + '/api/sysFile/uploadFile')
const fileHeader = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token')
})
// 表单数据
const formData = ref({
  name: '',
  code: '',
  contactPerson: '',
  phone: '',
  email: '',
  logo: '',
  province: '云南省',
  city: '昆明市',
  address: '',
  businessLicenseNo: '',
  isEnabled: true,
  rating: 4.8,
  businessHours: '10:00 - 22:00',
  averageCost: 120,
  tagsJson: '["中餐","老字号","推荐"]',
  category: '餐饮',
  position: '39.906712,116.397481',
  imageUrls: '',
  description: '地道风味'
})

// 状态变量
const inputVisible = ref(false)
const inputValue = ref('')
const imageFileList = ref<UploadFile[]>([])

// 标签管理
const tags = computed({
  get: () => {
    try {
      let temp = JSON.parse(formData.value.tagsJson)
      // while (typeof temp == 'string') {
      //   temp = JSON.parse(temp)
      // }
      // console.log(typeof temp)git
      return temp // JSON.parse(formData.value.tagsJson || '[]')
    } catch {
      return []
    }
  },
  set: (value: string[]) => {
    formData.value.tagsJson = JSON.stringify(value)
  }
})

const handleLogoSuccess = (response: any, file: UploadFile) => {
  // console.log('Logo上传结果:', response)
  let { code, message, result } = response
  if (code === 200) {
    let url = `${host}/${result.url}`
    formData.value.logo = url
    console.log('Logo上传成功:', formData.value.logo)
    ElMessage.success('Logo上传成功')
  } else {
    ElMessage.error('Logo上传失败: ' + response.message)
  }
}

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入商家名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  // contactPerson: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  // phone: [
  //   { required: true, message: '请输入联系电话', trigger: 'blur' },
  //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  // ],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  category: [{ required: true, message: '请选择商家分类', trigger: 'change' }]
}

// Logo上传处理
const beforeLogoUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('Logo只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传处理
const beforeImageUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleImageUpload = (response: any, file: UploadFile) => {
  let { code, message, result } = response
  if (code === 200) {
    let url = `${host}/${result.url}` // 假设返回的结果中包含图片的URL

    const currentImages = JSON.parse(formData.value.imageUrls || '[]')
    currentImages.push(url)
    formData.value.imageUrls = JSON.stringify(currentImages)

    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败: ' + message)
  }
}

const handleImageRemove = (file: UploadFile) => {
  const currentImages = JSON.parse(formData.value.imageUrls || '[]')
  const index = imageFileList.value.findIndex((item) => item.uid === file.uid)
  if (index > -1) {
    currentImages.splice(index, 1)
    formData.value.imageUrls = JSON.stringify(currentImages)
  }
}

// 标签管理
const removeTag = (tag: string) => {
  const newTags = tags.value.filter((t: string) => t !== tag)
  tags.value = newTags
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !tags.value.includes(inputValue.value)) {
    tags.value = [...tags.value, inputValue.value]
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...formData.value
    }
    if (editMode.value) {
      submitUpdate(submitData)
    } else {
      submitCreate(submitData)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

const submitCreate = (submitData: any) => {
  // API调用
  http
    .create(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('发布成功！')
      dialogVisible.value = false
      emit('create', submitData)
    })
    .catch(() => {
      ElMessage.error('发布失败，请稍后重试')
    })
}
const submitUpdate = (submitData: any) => {
  let keys = ['updateTime', 'updateUserId', 'updateUserName', 'userId']
  keys.forEach((t) => delete submitData[t])
  submitData.status = submitData.status ?? 100
  http
    .update(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      emit('update', submitData)
    })
    .catch(() => {
      ElMessage.error('更新失败，请稍后重试')
    })
}

const emit = defineEmits(['update', 'create'])
const editMode = ref(false)
const dialogVisible = ref(false)
const handleCreate = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增数据'
  editMode.value = false
  imageFileList.value = []
  formData.value = {
    name: '',
    code: '',
    contactPerson: '',
    phone: '',
    email: '',
    logo: '',
    province: '云南省',
    city: '昆明市',
    address: '',
    businessLicenseNo: '',
    isEnabled: true,
    rating: 4.8,
    businessHours: '10:00 - 22:00',
    averageCost: 120,
    tagsJson: '',
    category: '餐饮',
    position: '39.906712,116.397481',
    imageUrls: '',
    description: ''
  }
}
const handleModify = (obj: any) => {
  dialogVisible.value = true
  formData.value = { ...obj }
  editMode.value = true
  dialogTitle.value = '编辑数据'
  // formData.value.tagsJson = JSON.parse(obj.tagsJson)
  imageFileList.value = []
  if (!obj.imageUrls) {
    return
  }
  let imgs = JSON.parse(obj.imageUrls)
  imgs.forEach((t: string, index: number) => {
    imageFileList.value.push({ uid: 100 + index, url: t, name: 'file_' + index, status: 'success' })
  })
  //   console.log(obj)
}

defineExpose({
  handleCreate,
  handleModify
})
</script>
<style>
.merchant-form-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.merchant-form {
  margin-top: 20px;
}

.upload-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.logo-uploader:hover {
  border-color: #409eff;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  text-align: center;
  line-height: 80px;
}

.logo-preview {
  width: 120px;
  height: 80px;
  object-fit: cover;
  display: block;
}

.image-upload-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.tags-section {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-input {
  width: 120px;
}

.new-tag-btn {
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
  border-style: dashed;
}

.form-actions {
  padding: 20px 0px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.preview-json {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.5;
  max-height: 400px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .merchant-form-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>
